package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.User;
import util.db.DBhelp;
import util.db.Page;
import util.db.RowMapper;

public class UserDao {

	DBhelp<User> dBhelp = new DBhelp<User>();
	
	
	private class userRowMapper implements RowMapper<User>{

		public User mapRow(ResultSet resultSet) throws SQLException {
			User user = new User();
			user.setId(resultSet.getString("id"));
			user.setUsername(resultSet.getString("username"));
			user.setPassword(resultSet.getString("password"));
			user.setEmail(resultSet.getString("email"));
			user.setIp(resultSet.getString("ip"));
			user.setLastaccesstime(resultSet.getString("lastaccesstime"));
			user.setPic(resultSet.getString("pic"));
			user.setCreatetime(resultSet.getString("createtime"));
			user.setActive(resultSet.getBoolean("active"));
			user.setEnable(resultSet.getBoolean("enable"));
			return user;
		}
		
		
	}


	public void save(User user) {
		String sql = "insert into t_user (id,username,password,email,ip,lastaccesstime,pic,createtime,active,enable)values(?,?,?,?,?,?,?,?,?,?)";
		dBhelp.update(sql, user.getId(),user.getUsername(),user.getPassword(),user.getEmail(),user.getIp(),user.getLastaccesstime(),user.getPic(),user.getCreatetime(),user.isActive(),user.isEnable());
	}


	public User findUserById(String id) {
		String sql = "select * from t_user where id=?";
		return dBhelp.executeQueryToObject(sql, new userRowMapper(), id);
	}


	public void update(User user) {
		String sql = "update t_user set username=?,password=?,email=?,ip=?,lastaccesstime=?,pic=?,createtime=?,active=?,enable=? where id=?";
		dBhelp.update(sql, user.getUsername(),user.getPassword(),user.getEmail(),user.getIp(),user.getLastaccesstime(),user.getPic(),user.getCreatetime(),user.isActive(),user.isEnable(),user.getId());
		
	}


	public User findUserByName(String username) {
		String sql = "select * from t_user where username=?";
		return dBhelp.executeQueryToObject(sql, new userRowMapper(), username);
	}
	
	

	public Page<User> findAllUser(int nowPageNum) {
		Page<User> page = new Page<User>(nowPageNum, countAllUser());
		String sql = "select * from t_user order by createtime desc limit ?,?";
		List<User> list = dBhelp.executeQueryForList(sql, new userRowMapper(), page.getStartPage(),page.getPagesize());
		page.setList(list);
		return page;
	}


	private int countAllUser() {
		String sql = "select count(*) from t_user";
		return dBhelp.executeQuery(sql).intValue();
	}
}
